#include "formcontent.h"
#include "ui_formcontent.h"
#include "widgetuart.h"
#include "widgetrs485.h"
#include "widgetmodbus.h"
#include "widgetiic.h"
#include "widgetcan.h"
#include "widgetsteeringuart.h"
#include "widgetsteeringmodbus.h"
#include "widgetsteeringiic.h"
#include "formcontent.h"
#include "widget420.h"
#include <QString>
#include "maindialog.h"


FormContent::FormContent(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormContent)
{

    InitSerialSlots();

    InitCanbusSlots();

    ui->setupUi(this);


    displayChart_ = new QChart;
    chartView_ = new QChartView(displayChart_);
    chartView_->setRubberBand(QChartView::RectangleRubberBand);

    dataSeries_ = new QLineSeries;
    displayChart_->addSeries(dataSeries_);

    dataSeries_->setUseOpenGL(true);

    axisX = new QValueAxis;
    axisX->setRange(0, 1.0 * MAXDISPTIME);
    axisX->setLabelFormat("%g");
    axisX->setTitleText(tr("Time") + "(s)");
    axisY = new QValueAxis;
    axisY->setRange(0, 35000.00);
    axisY->setTitleText(tr("Distance") + "(cm)");

    displayChart_->setAxisX(axisX, dataSeries_);
    displayChart_->setAxisY(axisY, dataSeries_);
    displayChart_->legend()->hide();

    ui->layoutChart->addWidget(chartView_);

    ui->lbCANChan->setVisible(false);
    ui->cbCanChan->setVisible(false);

    InitDatas();


    QSettings *settings = new QSettings("config.ini",QSettings::IniFormat);

    settings->beginGroup("UI");
    QString LANG = settings->value("LANG","").toString();
    settings->endGroup();

    if(LANG=="CN"||LANG=="")
    {
        ui->rbCN->setChecked(true);
        ui->rbEN->setChecked(false);
    }
    else if(LANG=="EN"){
        ui->rbEN->setChecked(true);
        ui->rbCN->setChecked(false);
    }

	delete settings;

}

FormContent::~FormContent()
{
    delete ui;
}

void FormContent::on_serialComboBox_currentIndexChanged(const QString &_selectedName)
{

}


QString FormContent::__file_browse()
{
    //定义文件对话框类
    QFileDialog fileDialog;

    //定义文件对话框标题
    fileDialog.setWindowTitle(tr(u8"打开文件"));

    //设置默认文件路径
    fileDialog.setDirectory(".");

    //设置只能选择一个文件。选择多个文件使用QFileDialog::ExistingFiles
    fileDialog.setFileMode(QFileDialog::ExistingFile);

    //设置视图模式
    fileDialog.setViewMode(QFileDialog::Detail);

    QStringList fileName;
    if(fileDialog.exec())
    {
        fileName = fileDialog.selectedFiles();
    }
    if(fileName.isEmpty())
    {
        return "";
    }
    return fileName.at(0);
}

void FormContent::InitSerialSlots()
{
    sensorRecver_ = new serialportio;
    workThread_ = new QThread;
    distUpdateTimer_ = new QTimer;
    distTimerModbus = new QTimer;
    distTimerIIC = new QTimer;

    timerSerialPortSearch = new QTimer;

    sensorRecver_->moveToThread(workThread_);
    sensorRecver_->serialPort_->moveToThread(workThread_);
    sensorRecver_->timer_->moveToThread(workThread_);


    qRegisterMetaType<StringVector>("StringVector");

    connect(sensorRecver_, SIGNAL(sigUpdateProcessbar(float)), this, SLOT(slotUpdateProcessbar(float)));
    connect(sensorRecver_, SIGNAL(signalDistance(QVector<uint16_t>,QVector<uint16_t>, const StringVector&,int)), this, SLOT(slotDisplay(QVector<uint16_t>,QVector<uint16_t>, const StringVector&,int)));
    connect(sensorRecver_, SIGNAL(sigUpdateProcessbar(float)), this, SLOT(slotUpdateProcessbar(float)));
    connect(distUpdateTimer_, SIGNAL(timeout()), this, SLOT(slotDistUpdate()));

    //主动发送的Timer
//    connect(distTimerModbus, SIGNAL(timeout()), this, SLOT(slotDistModbusUpdate()));
//    connect(distTimerIIC, SIGNAL(timeout()), this, SLOT(slotDistIICUpdate()));

    connect(timerSerialPortSearch, SIGNAL(timeout()), this, SLOT(slotSerialPortUpdate()));

    connect(sensorRecver_, SIGNAL(signalUpgradeResult(bool)), this, SLOT(slotUpgradeResult(bool)));

    connect(sensorRecver_, SIGNAL(signalDataContractRcv(QByteArray)), this, SLOT(slotUartDataContractRcv(QByteArray)));

    connect(sensorRecver_, SIGNAL(signalDataRcv(QByteArray)), this, SLOT(slotUartDataRcv(QByteArray)));

    connect(sensorRecver_, SIGNAL(signalSerialCmdSend(QByteArray)), this, SLOT(slotUartDataSend(QByteArray)));

    connect(sensorRecver_, SIGNAL(signalBaudrateChanged()), this, SLOT(slotBaudrateChanged()));

	connect(sensorRecver_, SIGNAL(signalOuputFormatChange(QString)), this, SLOT(slotOuputFormatChange(QString)));

    workThread_->start();

    v_freq.resize(FREQ_VEC_LENGTH);
    v_index = 0;

    distUpdateTimer_->start(TIM_FREQ_TIMEOUT);

    timerSerialPortSearch->start(2000);



}

void FormContent::InitCanbusSlots()
{
     canbusIo = new CanBusIoThread;

     distUpdateTimer_ = new QTimer;

      connect(distUpdateTimer_, SIGNAL(timeout()), this, SLOT(slotDistUpdate()));

//     connect(canbusIo, SIGNAL(sigUpdateProcessbar(float)), this, SLOT(slotUpdateProcessbar(float)));
      connect(canbusIo, SIGNAL(signalDistance(QVector<uint16_t>,QVector<uint16_t>, const StringVector&,int)), this, SLOT(slotDisplay(QVector<uint16_t>,QVector<uint16_t>, const StringVector&,int)));
//    connect(canbusIo, SIGNAL(sigUpdateProcessbar(float)), this, SLOT(slotUpdateProcessbar(float)));


       connect(canbusIo, SIGNAL(signalDataRcv(QByteArray)), this, SLOT(slotUartDataRcv(QByteArray)));
       connect(canbusIo, SIGNAL(signalSerialCmdSend(QByteArray)), this, SLOT(slotUartDataSend(QByteArray)));
//     connect(canbusIo, SIGNAL(signalBaudrateChanged()), this, SLOT(slotBaudrateChanged()));

     v_freq.resize(FREQ_VEC_LENGTH);
     v_index = 0;
     distUpdateTimer_->start(TIM_FREQ_TIMEOUT);


}

/**显示距离
 * @brief FormContent::slotDisplay
 * @param _dist
 * @param _amp
 * @param _freq
 */
void FormContent::slotDisplay(QVector<uint16_t> _dist, QVector<uint16_t> _amp, const StringVector& _hexRxFrames, int _freq)
{
    if (_freq == 0)
        return;
    int pointSkip = _freq < 100 ? 1 : _freq / 100;

    freq_ = _freq;

    if (suspend_)
        oldPoints_ = pointsTemp_;
    else
        oldPoints_ = dataSeries_->pointsVector();

    double timeThresh = currentTime_ + 1.0 * _dist.length() / _freq - maxDispTime_;
    if (timeThresh >= 0)
    {
        int i;
        for (i = 0; i < oldPoints_.length(); i++)
            if (oldPoints_.at(i).x() >= timeThresh)
                break;

        points_ = oldPoints_.mid(i, -1);
        timeThresh = oldPoints_.at(0).x();
    }
    else if (oldPoints_.length() > 0)
    {
        timeThresh = oldPoints_.at(0).x();
    }
    else
    {
        timeThresh = 0.0;
    }
    if (!suspend_)
        axisX->setRange(timeThresh, timeThresh + maxDispTime_);

    for (int i = 0; i < _dist.length(); i += pointSkip)
    {
        currentTime_ += 1.0 * pointSkip / _freq;
        dist_ = _dist.at(i) ; //cm

        //信号强度，huhao
        amp_ = _amp.at(i);

        bytesRxHex = _hexRxFrames.at(i);

        points_.append(QPointF(currentTime_, dist_));

        // 更新y轴范围
        maxDistAxis_ = 0;
        foreach(QPointF p, points_)
        {
            maxDistAxis_ = ((maxDistAxis_ >= p.y()) ? maxDistAxis_ : p.y());
        }
        if (!suspend_)
        {
            axisY->setRange(0, maxDistAxis_ / 0.9);
        }

        //日志文件记录
        if (recordFlg_)
        {
            //是否带时间戳
            QString strRecord = "";
            QString sDateStamp="";

            //带时间戳
            if(recordTimeStampFlg_){

                QDateTime current_date_time =QDateTime::currentDateTime();
                QString current_date =current_date_time.toString("yyyy.MM.dd hh:mm:ss.zzz");

                if(recordFormat==0)
                {
                    //Hex 原始数据
                    outStream_ <<current_date <<"   "<<bytesRxHex<< endl;
                    for (int j = 1; j < pointSkip && (i + j) < _dist.length(); j++)
                    {
                        outStream_ <<current_date <<"   "<<_hexRxFrames.at(i+j)<< endl;
                    }


                }
                else if (recordFormat==1) {

                    //Ascii 实际计算出的
                    outStream_ <<current_date <<" dist:"<< dist_ <<" strength:"<<amp_<< endl;
                    for (int j = 1; j < pointSkip && (i + j) < _dist.length(); j++)
                    {
                        outStream_ <<current_date <<" dist:"<< _dist.at(i + j)  <<" strength:"<<_amp.at(i + j) << endl;
                    }

                }


            }

            else
            {
                //不带时间戳
                if(recordFormat==0)
                {
                    //Hex 原始数据
                    outStream_<<bytesRxHex<< endl;
                    for (int j = 1; j < pointSkip && (i + j) < _dist.length(); j++)
                    {
                        outStream_<<_hexRxFrames.at(i+j)<< endl;
                    }


                }
                else if (recordFormat==1) {

                    //Ascii 实际计算出的
                    outStream_ <<" dist:"<< dist_ <<" strength:"<<amp_<< endl;
                    for (int j = 1; j < pointSkip && (i + j) < _dist.length(); j++)
                    {
                        outStream_<<" dist:"<< _dist.at(i + j)  <<"   strength:"<<_amp.at(i + j) << endl;
                    }

                }

            }

			
        }
    }

    if (suspend_)
        pointsTemp_ = points_;
    else
        dataSeries_->replace(points_);
}

void FormContent::slotDistUpdate()
{
    uint32_t i;
    v_freq[v_index % FREQ_VEC_LENGTH] = freq_;

    for(i = v_index + FREQ_VEC_LENGTH; i > v_index; i--)
    {
        if(v_freq.at(i % FREQ_VEC_LENGTH) != 0)
        {
            break;
        }
    }

    if(FREQ_VEC_LENGTH <= ++v_index)
    {
        v_index = 0;
    }

    ui->lbDistance->setText(tr("测量距离：")+QString::number(dist_));
    ui->lbSignal->setText(tr("信号强度:")+QString::number(amp_));
    ui->lbFreq->setText(tr("采样频率:")+QString::number(v_freq.at(i % FREQ_VEC_LENGTH), 10));
    freq_ = 0;
}




void FormContent::InitDatas()
{
    foreach(QSerialPortInfo info, QSerialPortInfo::availablePorts())
    {
         ui->cbComm->addItem(info.portName());
    }


    ui->cbBaudrate->clear();
//    ui->baudrateComboBox->addItem("");
    ui->cbBaudrate->addItem("9600");
    ui->cbBaudrate->addItem("14400");
    ui->cbBaudrate->addItem("19200");
    ui->cbBaudrate->addItem("38400");
    ui->cbBaudrate->addItem("56000");
    ui->cbBaudrate->addItem("57600");
    ui->cbBaudrate->addItem("115200");
    ui->cbBaudrate->addItem("128000");
    ui->cbBaudrate->addItem("230400");
    ui->cbBaudrate->addItem("256000");
    ui->cbBaudrate->addItem("460800");
    ui->cbBaudrate->addItem("512000");
    ui->cbBaudrate->addItem("750000");
    ui->cbBaudrate->addItem("921600");
    ui->cbBaudrate->setEditable(true);


    QList<QString> qDataList1;
    qDataList1.append(tr("UART"));
    qDataList1.append(tr("IIC"));
    qDataList1.append(tr("IO"));
    mapDatas.insert(tr("TF-Luna"),qDataList1);

    QList<QString> qDataList2;
    qDataList2.append(tr("UART"));
    qDataList2.append(tr("IIC"));
    qDataList2.append(tr("IO"));
    mapDatas.insert(tr("TFmini-S"),qDataList2);


    QList<QString> qDataList3;
    qDataList3.append(tr("RS485(Modbus)"));
    qDataList3.append(tr("CAN"));
    mapDatas.insert(tr("TFmini-i"),qDataList3);

    QList<QString> qDataList4;
    qDataList4.append(tr("UART"));
    qDataList4.append(tr("IIC"));
    qDataList4.append(tr("IO"));
    mapDatas.insert(tr("TFmini-Plus"),qDataList4);


    QList<QString> qDataList5;
    qDataList5.append(tr("UART"));
    qDataList5.append(tr("IIC"));
    qDataList5.append(tr("IO"));
    mapDatas.insert(tr("TF02-Pro"),qDataList5);


    QList<QString> qDataList6;
    qDataList6.append(tr("UART"));
    qDataList6.append(tr("IIC"));
    qDataList6.append(tr("RS485(Modbus)"));
    mapDatas.insert(tr("TF02-Pro-W"),qDataList6);



    QList<QString> qDataList7;
    qDataList7.append(tr("UART"));
    mapDatas.insert(tr("TF-LM40"),qDataList7);


    QList<QString> qDataList8;
    qDataList8.append(tr("RS485(Modbus)"));
    qDataList8.append(tr("CAN"));
    mapDatas.insert(tr("TF02-i"),qDataList8);


    QList<QString> qDataList9;
    qDataList9.append(tr("UART"));
    qDataList9.append(tr("RS232"));
    qDataList9.append(tr("RS485"));
    qDataList9.append(tr("RS485(Modbus)"));
    qDataList9.append(tr("4-20mA"));
    qDataList9.append(tr("CAN"));

    mapDatas.insert(tr("TF03"),qDataList9);

    foreach(QString s,mapDatas.keys())
    {
        ui->cbProductModal->addItem(s);
    }
}

void FormContent::on_cbProductModal_currentIndexChanged(const QString &s)
{
    ui->cbCommContract->clear();
    QString key = ui->cbProductModal->currentText();

    QList<QString> contractList = mapDatas[key];

    foreach(QString s,contractList)
    {
        ui->cbCommContract->addItem(s);
    }
}

void FormContent::on_btnConnTF_clicked()
{
      if(ui->cbCommContract->currentText()=="CAN")
      {

          if( ui->btnConnTF->text()=="连接")
          {
              if (!canbusIo->isOpen())
               {


                   try
                   {
                       //TODO
					   qDebug() << u8"连接设备===>" << "当前产品：" << ui->cbProductModal->currentText() << "当前接口：" << ui->cbCommContract->currentText()
						   << "DeviceType：" << ui->cbComm->currentText() << "波特率：" << ui->cbBaudrate->currentText().toInt();

                       QString devType = ui->cbComm->currentText();
                       uint deviceType = 4;
                       if(devType=="USBCAN1")
                       {
                           deviceType = 3;
                       }
                       uint deviceIndex = 0;
                       uint chanIndex = ui->cbCanChan->currentIndex();

                       uint baudrate = ui->cbBaudrate->currentText().remove("kbps").toUInt();

                       if (canbusIo->OpenCAN(deviceType,deviceIndex,chanIndex, baudrate))
                       {
                           ui->btnConnTF->setText(tr("断开"));
                           ui->cbComm->setEnabled(false);
                           ui->cbBaudrate->setEnabled(false);

                           canbusIo->start();
                       }
                       else
                       {
                            QMessageBox::warning(NULL, "提示", tr(u8"打开CAN失败"));
                            qDebug(u8"连接失败!");
                       }
                   }
                   catch (QString exception)
                   {
                       qDebug()<<exception;
                   }
               }
               else
               {
                   ui->btnConnTF->setText(tr("断开"));
                   qDebug(u8"CAN已经打开!");
               }
          }
          else {
              ////////断开//////////////////
              if (canbusIo->isOpen())
               {
                   try
                   {
					   qDebug() << u8"断开设备===>" << "当前产品：" << ui->cbProductModal->currentText() << "当前接口：" << ui->cbCommContract->currentText()
						   << "DeviceType：" << ui->cbComm->currentText() << "波特率：" << ui->cbBaudrate->currentText().toInt();

                      canbusIo->stopped = true;

                      if (canbusIo->CloseCAN())
                      {
                          ui->btnConnTF->setText(tr("连接"));
                          ui->cbComm->setEnabled(true);
                          ui->cbBaudrate->setEnabled(true);
                      }
                       else
                       {
                          QMessageBox::warning(NULL, "提示", tr(u8"断开CAN失败"));
                          qDebug(u8"断开失败!");
                       }
                   }
                   catch (QString exception)
                   {
                       qDebug()<<exception;
                   }
               }
               else
               {
                   ui->btnConnTF->setText(tr("连接"));
                   qDebug("CAN已经断开!");
               }


          }


      }

      else {


          if( ui->btnConnTF->text()=="连接")
          {
              if (!sensorRecver_->isOpen())
               {
				  qDebug()<< u8"连接设备===>"<<"当前产品："<<ui->cbProductModal->currentText()<<"当前接口："<<ui->cbCommContract->currentText()
					  <<"串口号："<< ui->cbComm->currentText()<<"波特率："<< ui->cbBaudrate->currentText().toInt();
                   try
                   {
                       serialSelected_ =  ui->cbComm->currentText();
                       baudRate_ = ui->cbBaudrate->currentText().toInt();
                     
                       if (sensorRecver_->open(serialSelected_, baudRate_))
                       {
                           ui->btnConnTF->setText(tr("断开"));
                           ui->cbComm->setEnabled(false);
                           ui->cbBaudrate->setEnabled(false);

						   qDebug(u8"连接成功!");
                       }
                       else
                       {
                          qDebug(u8"连接失败!");

						  QMessageBox::warning(NULL, "提示", tr(u8"串口连接失败，可能被其他程序占用"));

                       }
                   }
                   catch (QString exception)
                   {
                       qDebug()<<exception;
                   }
               }
               else
               {
                   ui->btnConnTF->setText(tr("断开"));
				 
               }
          }
          else {
              ////////断开//////////////////
              if (sensorRecver_->isOpen())
               {
                   try
                   {
					   qDebug() << u8"断开设备===>" << "当前产品：" << ui->cbProductModal->currentText() << "当前接口：" << ui->cbCommContract->currentText()
						   << "串口号：" << ui->cbComm->currentText() << "波特率：" << ui->cbBaudrate->currentText().toInt();

                      if (sensorRecver_->close())
                      {
                          ui->btnConnTF->setText(tr("连接"));
                          ui->cbComm->setEnabled(true);
                          ui->cbBaudrate->setEnabled(true);

						  
                      }
                       else
                       {
                          qDebug(u8"断开失败!");
						  QMessageBox::warning(NULL, "提示", tr(u8"串口断开失败"));
                       }
                   }
                   catch (QString exception)
                   {
					   QMessageBox::warning(NULL, "提示", exception);
                       qDebug()<<exception;
                   }
               }
               else
               {
                   ui->btnConnTF->setText(tr("连接"));
                   qDebug(u8"COM已经连接!");
               }


          }


      }


}


void FormContent::on_cbCommContract_currentIndexChanged(const QString &arg1)
{

    if(widgetFunc!=nullptr)
    {
        //ui->layoutContent->removeWidget(formContent);
        widgetFunc->close();
        widgetFunc = nullptr;
    }


    if(arg1=="CAN")
    {


        ui->lbCANChan->setVisible(true);
        ui->cbCanChan->setVisible(true);

        ui->cbBaudrate->clear();
        ui->cbBaudrate->addItem("5kbps");
        ui->cbBaudrate->addItem("10kbps");
        ui->cbBaudrate->addItem("20kbps");
        ui->cbBaudrate->addItem("50kbps");
        ui->cbBaudrate->addItem("100kbps");
        ui->cbBaudrate->addItem("125kbps");
        ui->cbBaudrate->addItem("250kbps");
        ui->cbBaudrate->addItem("500kbps");
        ui->cbBaudrate->addItem("800kbps");
        ui->cbBaudrate->addItem("1000kbps");
        ui->cbBaudrate->setEditable(false);

        ui->lbComTitle->setText(tr("CAN接口类型"));

        ui->cbComm->clear();
        ui->cbComm->addItem("USBCAN1");
        ui->cbComm->addItem("USBCAN2");

        ui->cbComm->setCurrentIndex(1);
		ui->cbBaudrate->setCurrentIndex(6);

    }
	else 
	{

        ui->lbCANChan->setVisible(false);
        ui->cbCanChan->setVisible(false);

        ui->cbBaudrate->clear();

        ui->cbBaudrate->addItem("9600");
        ui->cbBaudrate->addItem("14400");
        ui->cbBaudrate->addItem("19200");
        ui->cbBaudrate->addItem("38400");
        ui->cbBaudrate->addItem("56000");
        ui->cbBaudrate->addItem("57600");
        ui->cbBaudrate->addItem("115200");
        ui->cbBaudrate->addItem("128000");
        ui->cbBaudrate->addItem("230400");
        ui->cbBaudrate->addItem("256000");
        ui->cbBaudrate->addItem("460800");
        ui->cbBaudrate->addItem("512000");
        ui->cbBaudrate->addItem("750000");
        ui->cbBaudrate->addItem("921600");

		ui->lbComTitle->setText(tr("接口协议"));

		ui->cbComm->clear();

		ui->cbBaudrate->setCurrentIndex(6);
        ui->cbBaudrate->setEditable(true);

    }

    if(ui->cbProductModal->currentText()==QString("TF02-Pro-W")||ui->cbProductModal->currentText()==QString("TF-LM40"))
    {
        if(ui->cbCommContract->currentText()=="UART")
        {
            widgetFunc = new WidgetSteeringUart;

           ((WidgetSteeringUart*)widgetFunc)->SetUartRecerver(this->sensorRecver_,ui->cbProductModal->currentText());
        }
        else if(ui->cbCommContract->currentText()=="RS485(Modbus)")
        {
            widgetFunc = new WidgetSteeringModbus;

            ((WidgetSteeringModbus*)widgetFunc)->SetUartRecerver(this->sensorRecver_,ui->cbProductModal->currentText());

        }
        else if(ui->cbCommContract->currentText()=="IIC")
        {
            widgetFunc = new WidgetSteeringIIC;

            ((WidgetSteeringIIC*)widgetFunc)->SetUartRecerver(this->sensorRecver_,ui->cbProductModal->currentText());
        }
    }
    else
    {
        if(ui->cbCommContract->currentText()=="UART"||ui->cbCommContract->currentText()=="IO")
        {
             widgetFunc = new WidgetUart;

            ((WidgetUart*)widgetFunc)->SetUartRecerver(this->sensorRecver_,ui->cbProductModal->currentText());

        }
        else if(ui->cbCommContract->currentText()=="RS485"||ui->cbCommContract->currentText()=="RS232")
        {
             widgetFunc = new WidgetRs485;
            ((WidgetRs485*)widgetFunc)->SetUartRecerver(this->sensorRecver_,ui->cbProductModal->currentText());

        }
        else if(ui->cbCommContract->currentText()=="RS485(Modbus)")
        {
            widgetFunc = new WidgetModbus;
            ((WidgetModbus*)widgetFunc)->SetUartRecerver(this->sensorRecver_,ui->cbProductModal->currentText());

        }
        else if(ui->cbCommContract->currentText()=="IIC")
        {
            widgetFunc = new WidgetIIC;
            ((WidgetIIC*)widgetFunc)->SetUartRecerver(this->sensorRecver_,ui->cbProductModal->currentText());

        }
        else if(ui->cbCommContract->currentText()=="CAN")
        {
            widgetFunc = new WidgetCAN;
           ((WidgetCAN*)widgetFunc)->SetCanbusIo(this->canbusIo,ui->cbProductModal->currentText());

        }
        else if(ui->cbCommContract->currentText()=="4-20mA")
        {
            widgetFunc = new Widget420;
           ((Widget420*)widgetFunc)->SetUartRecerver(this->sensorRecver_,ui->cbProductModal->currentText());

        }

    }

    ui->layoutFuncPanel->addWidget(widgetFunc,1,Qt::AlignTop);

}



void FormContent::on_btnOpenFirmware_clicked()
{
     ui->etPath->setText(__file_browse());
}

void FormContent::on_btnUpgrade_clicked()
{
       QString fullpath = ui->etPath->text();
       if(fullpath.isEmpty())
       {
           QMessageBox box;
           box.setText(tr(u8"警告：文件路径不能为空！"));
           box.exec();
           return;
       }

       ui->lbProgress->setText(tr(u8"已完成0%"));

	   qDebug()<<"开始升级，Firmware路径"<< ui->etPath->text();

       sensorRecver_->upgrade(fullpath, upgrade_frame_length);
}

void FormContent::slotUpdateProcessbar(float value)
{
     QString progressInfo ="";

     ui->lbProgress->setText(progressInfo.sprintf(u8"已完成0%",value));

}


void FormContent::slotSerialPortUpdate()
{
    if(ui->cbCommContract->currentText()=="CAN")
    {
        return;
    }

    foreach(QSerialPortInfo info, QSerialPortInfo::availablePorts())
    {
        int i=0;
        for (; i< ui->cbComm->count();i++) {

            if(ui->cbComm->itemText(i)==info.portName()){
                break;
            }

        }

        if(i==ui->cbComm->count()){

             ui->cbComm->addItem(info.portName());
        }


    }


}

void FormContent::slotUpgradeResult(bool result)
{



}

void FormContent::slotBaudrateChanged()
{

    if (sensorRecver_->close())
    {
        ui->btnConnTF->setText(tr("连接"));
        ui->btnConnTF->setEnabled(true);
        ui->cbComm->setEnabled(true);
        ui->cbBaudrate->setEnabled(true);

        QMessageBox::information(this,tr("提示"), tr(u8"波特率已改变，请选择新的波特率重新连接设备!"));
    }

}

void FormContent::slotUartDataSend(QByteArray cmd)
{
    QByteArray dataBuffer_;
    dataBuffer_.append(cmd);

    qDebug("uart cmd tx =>" + cmd.toHex(' '));

    QDateTime current_date_time =QDateTime::currentDateTime();
    QString current_date =current_date_time.toString("yyyy.MM.dd hh:mm:ss.zzz");

    if(dataBuffer_.count()!=0)
    {
        ui->listRxCmd->addItem(current_date+tr(u8":发送指令=>")+dataBuffer_.toHex(' '));
        ui->listRxCmd->scrollToBottom();
    }

}

//void FormContent::slotUartDataRcv(QByteArray cmd)
//{

//    try{
//        char header[2] = {0x59, 0x59};
//        QByteArray dataHeader_ = QByteArray(header, 2);
//        QByteArray dataBuffer_;
//       // dataBuffer_.append(cmd);

//        qDebug("uart cmd rx =>" + cmd.toHex(' '));

//        QDateTime current_date_time =QDateTime::currentDateTime();
//        QString current_date =current_date_time.toString("yyyy.MM.dd hh:mm:ss.zzz");

//        int32_t idx = 0;

//        for (; (idx = cmd.indexOf(dataHeader_, idx)) >= 0; idx++)
//        {
//          QByteArray& newDataBuffer_ = cmd.remove(idx,9);
//          dataBuffer_.clear();
//          dataBuffer_.append(newDataBuffer_);
//            //dataBuffer_ = dataBuffer_.remove(idx,9);
//        }

//        if(dataBuffer_.count()>0)
//        {
//            return;
//        }

//        //获取帧
//        idx = 0;
//        //检查是否是5A帧
//        idx = dataBuffer_.indexOf(0x5A,0);
//        if(idx = -1){
//            dataBuffer_.clear();
//            return;
//        }

//        dataBuffer_ = dataBuffer_.remove(0,idx);

//        if(dataBuffer_.count()!=0)
//        {
//            ui->listRxCmd->addItem(current_date+":接收指令=>"+dataBuffer_.toHex(' '));
//            ui->listRxCmd->scrollToBottom();
//        }
//    }
//    catch(QException ex){
//       qErrnoWarning(ex.what());
//    }



//}

void FormContent::slotUartDataRcv(QByteArray cmd)
{

        try{
            char header[2] = {0x59, 0x59};
            QByteArray dataHeader_ = QByteArray(header, 2);
            QByteArray dataBuffer_;
            dataBuffer_.append(cmd);

            qDebug("uart cmd rx =>" + cmd.toHex(' '));

            QDateTime current_date_time =QDateTime::currentDateTime();
            QString current_date =current_date_time.toString("yyyy.MM.dd hh:mm:ss.zzz");



            if(dataBuffer_.count()!=0)
            {
                ui->listRxCmd->addItem(current_date+":接收指令=>"+dataBuffer_.toHex(' '));
                ui->listRxCmd->scrollToBottom();
            }
        }
        catch(QException ex){
           qErrnoWarning(ex.what());
        }
}

void FormContent::slotUartDataContractRcv(QByteArray cmd)
{

    QByteArray dataBuffer_;

    dataBuffer_.append(cmd);

    qDebug("uart cmd rx =>" + cmd.toHex(' '));

    QDateTime current_date_time =QDateTime::currentDateTime();
    QString current_date =current_date_time.toString("yyyy.MM.dd hh:mm:ss.zzz");

    int index = dataBuffer_.indexOf(0x5A,0);
    if(index<0) return;

    int framebytes = dataBuffer_.at(index+1);
    dataBuffer_ = dataBuffer_.remove(0,index);
    dataBuffer_ = dataBuffer_.remove(framebytes,dataBuffer_.count());

    if(dataBuffer_.count()!=0)
    {
        ui->listRxCmd->addItem(current_date+":接收指令=>"+dataBuffer_.toHex(' '));
        ui->listRxCmd->scrollToBottom();
    }



}



void FormContent::on_btnSave_clicked()
{

    QString fileName = ui->etFileName->text();

    if(!fileName.isNull())
    {
       if (!recordFlg_)
       {
		   qDebug() << "开始录制，保存路径" << fileName;

           QDateTime currentDate = QDateTime::currentDateTime();
           saveFile_.setFileName(fileName);
           if (saveFile_.open(QFile::WriteOnly | QFile::Truncate))
           {
               outStream_.setDevice(&saveFile_);
               recordFlg_ = true;
               ui->btnSave->setText(tr(u8"停止"));
           }
           else
           {
               QMessageBox::warning(this,tr("error"), tr(u8"请选择有效保存路径!"));
           }

       }
       else
       {
           recordFlg_ = false;
           ui->btnSave->setText(tr(u8"录制"));
           saveFile_.close();
       }


    }


}

void FormContent::on_btnFileSel_clicked()
{
    QString fileName;
    fileName =QFileDialog::getOpenFileName(this,
                                           tr("打开录制文件"),
                                            "D:\\" ,
                                           "Log Files(*.txt);;TEXT Files(*.txt);;All Files(*.*)");
    if(!fileName.isNull())
    {
        ui->etFileName->setText(fileName);
    }

}

void FormContent::on_btnSend_clicked()
{
    QString strTxCmd = ui->etTxCmd->text();

    QStringList cmdArr = strTxCmd.split(' ');
    QByteArray byteArr;
    foreach(QString s , cmdArr)
    {
        int byte2Tx = s.toInt(nullptr, 16);
        byteArr.append(byte2Tx);
    }

	if (ui->cbCommContract->currentText() == "CAN")
	{
		WidgetCAN* widgetCan = ((WidgetCAN*)widgetFunc);

		int CANID = widgetCan->GetCanTxId();

		if (!canbusIo->canOpen) {
			QMessageBox::warning(this, tr("error"), tr(u8"设备未连接!"));
			return;
		}

		bool bRet = canbusIo->sendCanData(CANID,byteArr);
		if (!bRet) {
			/*QDateTime current_date_time = QDateTime::currentDateTime();
			QString current_date = current_date_time.toString("yyyy.MM.dd hh:mm:ss.zzz");
			ui->listRxCmd->addItem(current_date + ":发送指令=>" + strTxCmd);
			ui->listRxCmd->scrollToBottom();*/
			QMessageBox::warning(this, tr("error"), tr(u8"未发送成功!"));
		}

	}
	else
	{
		bool bRet = sensorRecver_->send_uart_oneframe(byteArr);
		if (bRet) {
			QDateTime current_date_time = QDateTime::currentDateTime();
			QString current_date = current_date_time.toString("yyyy.MM.dd hh:mm:ss.zzz");
			ui->listRxCmd->addItem(current_date + ":发送指令=>" + strTxCmd);
			ui->listRxCmd->scrollToBottom();
		}
		else {
			QMessageBox::warning(this, tr("error"), tr(u8"未发送成功!"));
		}

	}


  

}

void FormContent::on_ckTimeStamp_stateChanged(int arg1)
{
    if(ui->ckTimeStamp->checkState()==Qt::CheckState::Checked){
        recordTimeStampFlg_=true;
    }else {
        recordTimeStampFlg_=false;
    }
}

void FormContent::on_rbHex_toggled(bool checked)
{
    if(checked){
        recordFormat= 1;
		qDebug() << "录制文件更改为Hex";
    }
}

void FormContent::on_rbAscii_toggled(bool checked)
{
    if(checked){
        recordFormat= 2;
		qDebug() << "录制文件更改为ASCII";
    }
}




void FormContent::on_btnReload_clicked()
{
    ui->cbComm->clear();

    foreach(QSerialPortInfo info, QSerialPortInfo::availablePorts())
    {
         ui->cbComm->addItem(info.portName());
    }

}


void FormContent::reboot()
{
	//QString program = QApplication::applicationFilePath();
	//QStringList arguments = QApplication::arguments();
	//QString workingDirectory = QDir::currentPath();
	//QProcess::startDetached(program, arguments, workingDirectory);
	//QApplication::exit();

	qApp->quit();   // 或者   aApp->closeAllWindows();
	QProcess::startDetached(qApp->applicationFilePath(), QStringList());


	

}

void FormContent::slotOuputFormatChange(QString changedFormat)
{

	qDebug() << "输出格式改变为"<< changedFormat;
	axisY->setTitleText(tr("Distance") + QString("(%1)").arg(changedFormat));

}


void FormContent::on_rbCN_clicked()
{
	QSettings *settings = new QSettings("config.ini", QSettings::IniFormat);

	QString langSet = settings->value("UI/LANG").toString();

	if (langSet == "CN")
	{
		delete settings;
		return;
	}

	QMessageBox messagbox(QMessageBox::NoIcon, tr(u8"提示"), tr(u8"切换语言需要重启程序，确定切换为中文版本么？"), QMessageBox::Yes | QMessageBox::No);
	int result = messagbox.exec();

	if (result == QMessageBox::Yes)
	{
	
		settings->setValue("UI/LANG", "CN");
		delete settings;
		reboot();
	}
	else
	{
		ui->rbCN->setChecked(false);
		ui->rbEN->setChecked(true);
	}

}

void FormContent::on_rbEN_clicked()
{
	QMessageBox messagbox(QMessageBox::NoIcon, "Info", "Switch Language Need Restart the Application，Sure to Switch and Restart？", QMessageBox::Yes | QMessageBox::No);
	int result = messagbox.exec();

	QSettings *settings = new QSettings("config.ini", QSettings::IniFormat);
	QString langSet = settings->value("UI/LANG").toString();

	if (langSet == "EN")
	{
		delete settings;
		return;
	}

	if (result == QMessageBox::Yes)
	{
		QSettings *settings = new QSettings("config.ini", QSettings::IniFormat);
		settings->setValue("UI/LANG", "EN");
		delete settings;
		reboot();
	}
	else
	{
		ui->rbCN->setChecked(true);
		ui->rbEN->setChecked(false);
	}
}




